
import { isEqual } from 'lodash/isEqual';

import memoizeOne from 'memoize-one';
import { queryMenu, queryButton } from '@/services/menu';

const groupBy = (data: Array<any>): Array<any> => {
  // const par = [];
  // const subP = {};
  // const sub = Array.isArray(data)
  //   ? data.reduce((r, a) => {
  //     const { parentId = '-1', depth, path, kind, type, orderNo, ...res } = a;
  //     if (+depth > 3) {
  //       r[parentId] = [...r[parentId] || [], { ...res }]
  //     } else if (+depth === 3) {
  //       if (!subP[parentId]) subP[parentId] = [];

  //       subP[parentId].push({ ...res })

  //     } else if (+depth === 2) {
  //       par.push(res.id)
  //     }
  //     return r;
  //   }, {})
  //   : [];

  // const menu = Array.isArray(par) && par[0] ? subP[par[0]] : [];

  // return Array.isArray(menu) ? menu.map(v => ({
  //   ...v,
  //   children: sub[v.id]
  // })) : [];
  const parent = data && Array.isArray(data) && data.filter((item, index) => +item.depth === 3)
  const res = Array.isArray(parent) && parent.map((item) => {
    const children = []
    Array.isArray(data) && data.forEach(v => {
      if (item.id === v.parentId) {
        children.push(v)
      }
    })
    return {
      ...item,
      children
    }
  })
  return res
}

const formatter = (data: Array<any>): Array<any> => {

  const menu = groupBy(data);
  return menu;
}

const memoizeOneFormtter = memoizeOne(formatter, isEqual)

export default {
  namespace: 'menu',

  state: {
    menuData: [],
    buttons: []
  },

  effects: {
    *queryMenu(_, { call, put }) {
      const response = yield call(queryMenu);
      const menu = memoizeOneFormtter(response);

      yield put({
        type: 'setMenu',
        payload: menu
      });
    },

    *queryButton({ payload }, { call, put }) {
      const response = yield call(queryButton, payload);

      yield put({
        type: 'setButton',
        payload: response
      })
    }
  },

  reducers: {
    setMenu(state, action) {
      return {
        ...state,
        menuData: action.payload
      }
    },
    setButton(state, action) {
      return {
        ...state,
        buttons: action.payload
      }
    }
  }
}
